//时间格式化函数,使用前必须定义
Date.prototype.format = function(format){
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    };

    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    };

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    };
    return format;
};
let client;
let one_second = 1000;
let timeArray = [""];
let tempArray = ["0"];
let speedArray = ["0"];
let timeText;
let flag = 60;
let message;

const config = {
    "host": "121.41.16.81",
    "port": 8083,
    "clientId":"OPENID",
    "userName":"CLF022C3AE839QWPG", // 网关ID
    "password":"123456abc",
    "timeout": 10,
    "keepalive": 1000
};
let errorInfo = {
    "inner_sensor_err":1,
    "inner_sensor_temp_alarm":0,
    "external_sensor_err":0,
    "external_sensor_over_temp":1,
    "mechanical_limit_temp_over_temp":0,
    "mechanical_limit_sensor_err":0,
    "motor_stalling":0,
    "external_sensor_drop":1,
    "end_of_time":0,
    "external_sensor_not_plugged":0
};
let statusPic = {
    "err": '<img src="../../public/html/button.png" alt="">',
    "good": '<img src="../../public/html/button_good.png" alt="">'
}
let options = {
    invocationContext: {
        host: config.host,
        port: config.port,
        clientId: config.clientId
    },
    timeout: config.timeout,
    keepAliveInterval: config.keepalive,
    userName: config.userName,
    password: config.password,
    onSuccess: onConnect,
    onFailure: function (e) {
        console.log(e);
    }
};
function addData(data) {
    if(data.data.speed === "" || data.data.temp === ""){}
    else {
        timeText = new Date().format("hh:mm:ss");
        timeArray.push(timeText);
        tempArray.push(data.data.temp);
        speedArray.push(data.data.speed);
        if (flag > 0) {
            flag--;
        } else {
            timeArray.shift();
            tempArray.shift();
            speedArray.shift();
        }
    }
};
function ledDisplay() {
    client = new Paho.Client( config.host, config.port,config.clientId );
    client.onConnected = onConnected;
    client.onMessageArrived = onMessageArrived;
    client.connect(options);
};
function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
    client.subscribe("GATEWAY/data");
    console.log("onConnect");
};
function onConnected() {
    console.log("success");
};
function onMessageArrived(msg) {

    /*You should receive message like this.
    {
        "state": "6",
        "safeTemp":"349",
        "time":"01:00",
        "speed":"400",
        "temp":"29.8",
        "setTemp":"40",
        "setSpeed":"500"
    }
    */
    message = JSON.parse(msg.payloadString);
    errorInfo = getDeviceAlarm(parseInt(message.data.errorInfo));
    document.getElementById('state').innerHTML = message.data.state;
    document.getElementById('safeTemp').innerHTML = message.data.tempmax;
    document.getElementById('time').innerHTML = message.data.Hour+":"+message.data.Min;
    document.getElementById('temp').innerHTML = message.data.temp;
    document.getElementById('speed').innerHTML = message.data.speed;
    document.getElementById('setTemp').innerHTML = message.data.tempset;
    document.getElementById('setSpeed').innerHTML = message.data.speedset;

};

function getDeviceAlarm(e) {
    errorInfo.inner_sensor_err = e & 32768;
    errorInfo.inner_sensor_temp_alarm = e & 16384;
    errorInfo.external_sensor_err = e & 8192;
    errorInfo.external_sensor_over_temp = e & 4096;
    errorInfo.mechanical_limit_temp_over_temp = e & 2048;
    errorInfo.mechanical_limit_sensor_err = e & 1024;
    errorInfo.motor_stalling = e & 512;
    errorInfo.external_sensor_drop = e & 256;
    errorInfo.end_of_time = e & 128;
    errorInfo.external_sensor_not_plugged = e & 64;
    return errorInfo;
}


// ######
let safeTempIndex = "safeTemp";
function newMarkline (msg) {
    return {
        data: [
            {
                silent: false,
                lineStyle:{
                    type: "solid",
                    color: "#bf1818",
                },
                label: {
                    position: 'middle',
                    formatter: 'safeTemp'
                }
                // yAxis: msg.safeTemp
            }
        ]
    }
};

ledDisplay();
setInterval(function () {
    let tempOption = {
        title:{
            text: '实时温度曲线'
        },
        tooltip:{
            trigger: 'axis'
        },
        legend:{
            data:["温度"]
        },
        toolbox: {
            show: true,
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                dataView: {readOnly: false},
                restore: {}
            }
        },
        xAxis:{
            data:timeArray
        },
        yAxis:{
            type: 'value',
            axisLabel: {
                formatter: '{value} °C'
            }
        },
        series:[
            {
                name:'温度',
                type:'line',
                data:tempArray,
                smooth: true,
                markLine: {
                    data: [
                        {
                            silent: false,
                            lineStyle:{
                                type: "solid",
                                color: "#bf1818",
                            },
                            label: {
                                position: 'middle',
                                formatter: 'safeTemp'
                            },
                            yAxis: message.data.tempmax
                        }
                    ]
                }
            }
        ]
    };
    let speedOption = {
        title:{
            text: '实时速度曲线'
        },
        tooltip:{
            trigger: 'axis'
        },
        legend:{
            data:['温度']
        },
        xAxis:{
            data:timeArray
        },
        yAxis:{},
        series:[
            {
                name:'速度',
                type:'line',
                data:speedArray,
                smooth: true
            }
        ]
    };
    addData(message, true);
    temp.setOption(tempOption);
    speed.setOption(speedOption);
}, 1000);
